﻿using System;
using System.Collections.Generic;

namespace Miao
{
    internal class ModuleManager
    {
        /// <summary>
        /// 按模块初始化顺序排列
        /// </summary>
        private readonly List<IModule> moduleList = new List<IModule>();
        private readonly Dictionary<Type, int> moduleCacheDictionary = new Dictionary<Type, int>();

        public T GetModule<T>() where T : IModule
        {
            if (moduleCacheDictionary.TryGetValue(typeof(T), out int index))
            {
                return (T)moduleList[index];
            }
            for (int i = 0; i < moduleList.Count; i++)
            {
                if (moduleList[i] is not T) continue;
                moduleCacheDictionary.Add(typeof(T), i);
                return (T)moduleList[i];
            }
            return default;
        }

        internal void AddModule<T>(T module) where T : IModule
        {
            moduleList.Add(module);
        }

        internal void EnsureCapacity(int capacity)
        {
            moduleList.Capacity = capacity;
            moduleCacheDictionary.EnsureCapacity(capacity);
        }
    }
}